package com.alliky.core.ext

import android.annotation.TargetApi
import android.app.Activity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.core.content.ContextCompat

/**
 * ================================================
 * @Description: 描述
 * @Author: wxianing
 * @Date: 2022/11/10 11:22
 * ================================================
 */

/**
 * 获取当前activity的ViewRoot
 *
 * @return
 */
fun Activity.getRootView(): View? {
    return (this.findViewById(android.R.id.content) as? ViewGroup)?.getChildAt(0)
}

fun Activity.getContentLayout(): FrameLayout? {
    return (this.findViewById(android.R.id.content) as? FrameLayout)
}

/**
 * 隐藏系统输入法
 */
fun EditText.hideKeyboard() {
    val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java)
    if (imm?.isActive == true) {
        imm.hideSoftInputFromWindow(applicationWindowToken, 0)
    }
}

/**
 * 禁用系统键盘
 */
@TargetApi(11)
fun EditText.disableSystemKeyboard() {
    try {
        val cls = EditText::class.java
        val setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", Boolean::class.java)
        setShowSoftInputOnFocus.isAccessible = true
        setShowSoftInputOnFocus.invoke(this, false)
    } catch (e: Exception) {
    }
}


/***
 * 设置延迟时间的View扩展
 * @param delay Long 延迟时间，默认600毫秒
 * @return T
 */
fun <T : View> T.withTrigger(delay: Long = 600): T {
    triggerDelay = delay
    return this
}

/***
 * 点击事件的View扩展
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
fun <T : View> T.click(block: (T) -> Unit) = setOnClickListener {
    block(it as T)
}

/***
 * 带延迟过滤的点击事件View扩展
 * @param delay Long 延迟时间，默认600毫秒
 * @param block: (T) -> Unit 函数
 * @return Unit
 */
fun <T : View> T.clickWithTrigger(time: Long = 600, block: (T) -> Unit) {
    triggerDelay = time
    setOnClickListener {
        if (clickEnable()) {
            block(it as T)
        }
    }
}

private var <T : View> T.triggerLastTime: Long
    get() = if (getTag(1123460103) != null) getTag(1123460103) as Long else -601
    set(value) {
        setTag(1123460103, value)
    }

private var <T : View> T.triggerDelay: Long
    get() = if (getTag(1123461123) != null) getTag(1123461123) as Long else 600
    set(value) {
        setTag(1123461123, value)
    }

private fun <T : View> T.clickEnable(): Boolean {
    var flag = false
    val currentClickTime = System.currentTimeMillis()
    if (currentClickTime - triggerLastTime >= triggerDelay) {
        triggerLastTime = currentClickTime
        flag = true
    }

    return flag
}

/***
 * 带延迟过滤的点击事件监听，见[View.OnClickListener]
 * 延迟时间根据triggerDelay获取：600毫秒，不能动态设置
 */
interface OnLazyClickListener : View.OnClickListener {

    override fun onClick(v: View?) {
        if (v?.clickEnable() == true) {
            onLazyClick(v)
        }
    }

    fun onLazyClick(v: View)
}

